<template>
  <view class="address-panel">
    <view class="title">配送至</view>
    <scroll-view class="list" scroll-y>
      <radio-group @change="selectAddrChange">
        <label class="item" v-for="(addrItem, addrIdx) in addressList" :key="addrIdx">
          <view>
            <radio style="transform:scale(0.8)" :value="addrItem.id + ''"></radio>
            <text class="content">{{ assembleAddress(addrItem) }}</text>
            <uni-tag :text="matchAddrLabel(addrItem.label)" v-if="addrItem.label" type="primary"></uni-tag>
          </view>
        </label>
      </radio-group>
    </scroll-view>
    <view class="confirm-btn">
      <button  type="info" size="mini" @click="createAddress">新建收货地址</button>
      <button  type="warn" size="mini" @click="confirmAddr">确定</button>
    </view>
  </view>
</template>
<script setup lang="ts">
import {ref} from "vue";
import {assembleAddress} from "@/utils/str";
import type {AddressLabelType} from "@/types/user";
import {AddressItemCls} from "@/pagesOrder/types/usercls";

// 定义接收的数据
defineProps({
  addressList: Array<AddressItemCls>
})
// 子组件与父组件的传值问题在vue3.4版本之后可以使用v-model代替props和emit，整体会更简洁
// 定义事件
const emit = defineEmits(['returnAddrEvent'])
const state = ref({
  selectedAddrId: 0,
  addrLabelList: [
    {label: "HOME", value: "家"},
    {label: "WORK", value: "公司"},
  ] as AddressLabelType[]
})

const selectAddrChange = (e: any) => {
  console.log("select addr:", e)
  state.value.selectedAddrId = e.detail.value
}

const matchAddrLabel = (itemLabel: string): string => {
  console.log("item label: ", itemLabel)
  for (let i = 0; i < state.value.addrLabelList.length; i++) {
    const tmpLabel = state.value.addrLabelList[i]
    console.log("label in match:", tmpLabel)
    if (tmpLabel.label === itemLabel) {
      return tmpLabel.value
    }
  }
  return ""
}
const confirmAddr = () => {
  console.log("click confirm addr btn ")
  // 触发事件并指定事件执行的动作
  emit("returnAddrEvent", getSelectedAddr())
}
const createAddress = () => {
  uni.navigateTo({
    url: "/pagesAddress/settings/settings"
  })
}
const getSelectedAddr = (): number => {
  console.log("return addr id ", state.value.selectedAddrId)
  // 将数据进行强制转换，否则返回的却是一个string类型
  return Number(state.value.selectedAddrId)
}

</script>
<style lang="scss">
.address-panel {
  .title {
    text-align: center;
    font-weight: bold;
    font-size: 19px;
    padding: 20px 0;
  }

  .list {
    padding-left: 20px;
    height: 220px;

    .item {
      padding-bottom: 10px;
      font-size: 14px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .content {
        margin-right: 10px;
      }
    }
  }

  .confirm-btn {
    margin-top: 20px;
    display: flex;
    align-items: center;
    border-radius: 10px;
  }
}
</style>